var express = require('express');
var router = express.Router();

var md5 = require("md5");
var fs=require("fs");
var conn= require('../conn');
var user_tab = require('../user_tab');

router.use(function (req, res, next) {
  if(req.session.islogin==true){
  	 next();
 	}else{
  		res.redirect("/login");
 	}
 
 });

/* GET home page. */
router.get('/MemberCenter', function(req, res, next) {
  	conn.query("select * from producttype",function(err,rows,fields){
	    var type = rows;
	    var urlList = req.url.substr(0,5);
  		res.render('MemberCenter', {type:type,url:urlList, title: '会员中心',users:req.session.username});
	});
});

router.get('/myOrder', function(req, res, next) {
	var ut= user_tab(req);
  	conn.query("select * from producttype",function(err,rows,fields){
	    var type = rows;
	    var urlList = req.url.substr(0,5);
		conn.query('select * from order_infro', function(err, rows, fields){
		 res.render('myOrder', {type:type,url:urlList, title: '我的订单',myorder:rows,usertab:ut.usertab,in_out:ut.in_out,link1:ut.link1,link2:ut.link2,order:ut.order});
		})
	});
});
router.get('/changePassword', function(req, res, next) {
  	conn.query("select * from producttype",function(err,rows,fields){
	    var type = rows;
	    var urlList = req.url.substr(0,5);
		res.render("changePassword",{ type:type,url:urlList,title:'修改密码'});
	});
});


router.post('/dochangePassword',function(req, res, next){
	req.body.olderPassword=md5(req.body.olderPassword);
	req.body.newPassword=md5(req.body.newPassword);
	req.body.password_again=md5(req.body.password_again);
	if(req.body.olderPassword==req.session.password) {
			if(req.body.newPassword==req.body.password_again) {
				var sql = 'update users set password="'+req.body.newPassword+'" where id='+req.session.user_id;
					console.log(sql);
			      conn.query(sql,function(err, rows, fields){
			      	
					res.send("修改成功！");
				})
			}else{
				res.send("您再次输入的密码不正确")
			}
	}else{
			res.send("您输入的旧密码不正确")
		}
   
 })

router.get('/delOrder', function(req, res, next) {
  conn.query('delete from order_infro where id='+req.query.id, function(err, rows, fields){

  res.redirect("myOrder");

  })
});


module.exports = router;
